package xin.alum.aim.coder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import xin.alum.aim.AIM;
import xin.alum.aim.model.Sent;
import xin.alum.aim.model.proto.Packet;
import xin.alum.aim.util.GZipUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Protobuf 协议转换
 *
 * @auther Alum(alum @ live.cn)
 * @date 2021/8/5 17:05
 */
public class ProtoDecoder extends ProtobufDecoder {

    public ProtoDecoder() {
        super(Packet.Sent.getDefaultInstance());
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) {
        ChannelPipeline pipeline = ctx.channel().pipeline();
        try {
            in = GZipUtil.ungzip(AIM.properties.getGzip(),in);
            super.decode(ctx, in, list);
            if (list.size() > 0) {
                List<Object> out = new ArrayList<>();
                list.forEach(p -> {
                    Packet.Sent m = (Packet.Sent) p;
                    Sent sent = new Sent();
                    sent.setKey(m.getKey());
                    sent.setTimestamp(m.getTimestamp());
                    sent.setData(m.getData());
                    out.add(sent);
                });
                list.clear();
                list.addAll(out);
            }
        } catch (Exception ex) {
            pipeline.remove(this);
            ctx.fireChannelRead(in);
        }

    }
}
